package com.yuan.pay_mall.controller;

import com.yuan.pay_mall.form.CartAddForm;
import com.yuan.pay_mall.form.CartUpdateForm;
import com.yuan.pay_mall.pojo.User;
import com.yuan.pay_mall.service.impl.CartServiceImpl;
import com.yuan.pay_mall.vo.CartVo;
import com.yuan.pay_mall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import static com.yuan.pay_mall.consts.MallConst.CURRENT_USER;

/*购物车*/
@RestController
public class CartController {
    /*表单统一验证*/
    /*  @Valid注解：用于校验，对于前端传进来的参数进行判断检查。其使用方法如下：
    在自定义的类中的字段上（参数字段），加上校验条件注解@NotNull
* */
    @Autowired
    private CartServiceImpl cartService;

    @GetMapping("/carts")
    public ResponseVo<CartVo> list(HttpSession session){//必传的字段若没有传，就不会执行到方法里面
        User user = (User)session.getAttribute(CURRENT_USER);
        return cartService.list(user.getId());
    }

    @PostMapping("/carts")
    public ResponseVo<CartVo> add(@Valid @RequestBody CartAddForm cartAddForm,
                                  HttpSession session){//必传的字段若没有传，就不会执行到方法里面
        User user = (User)session.getAttribute(CURRENT_USER);
        return cartService.add(user.getId(),cartAddForm);
    }
    @PutMapping(" /carts/{productId}")
    public ResponseVo<CartVo> update(@PathVariable Integer productId,
            @Valid @RequestBody CartUpdateForm from,
                                  HttpSession session){//必传的字段若没有传，就不会执行到方法里面
        User user = (User)session.getAttribute(CURRENT_USER);
        return cartService.update(user.getId(),productId,from);
    }
    @DeleteMapping("/carts/{productId}")
    public ResponseVo<CartVo> delete(@PathVariable Integer productId,
                                     HttpSession session){//必传的字段若没有传，就不会执行到方法里面
        User user = (User)session.getAttribute(CURRENT_USER);
        return cartService.delete(user.getId(),productId);
    }
    @PutMapping("/carts/selectAll")
    public ResponseVo<CartVo> selectAll(
                                     HttpSession session){//必传的字段若没有传，就不会执行到方法里面
        User user = (User)session.getAttribute(CURRENT_USER);
        return cartService.selectAll(user.getId());
    }
    @PutMapping("/carts/unSelectAll")
    public ResponseVo<CartVo> unSelectAll(
            HttpSession session){//必传的字段若没有传，就不会执行到方法里面
        User user = (User)session.getAttribute(CURRENT_USER);
        return cartService.unSelectAll(user.getId());
    }
    @GetMapping("/carts/products/sum")
    public ResponseVo<Integer> sum(HttpSession session){//必传的字段若没有传，就不会执行到方法里面
        User user = (User)session.getAttribute(CURRENT_USER);
        return cartService.sum(user.getId());
    }

}


